import pygame
# 设置随机方向
from random import *


# 定义小球类
class Ball(pygame.sprite.Sprite):
    def __init__(self, speed, position, bg_size, target):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(
            "./images/gray_ball.png").convert_alpha()
        # 定义绿色小球
        self.green_image = pygame.image.load(
            "./images/green_ball.png").convert_alpha()
        self.rect = self.image.get_rect()
        self.width, self.height = bg_size
        self.rect.left, self.rect.top = position
        self.side = [choice([-1, 1]), choice([-1, 1])]
        self.speed = speed
        self.radius = self.rect.width / 2
        self.target = target
        # 检查小球是否由玩家控制
        self.control = False
        # 判断是否发生碰撞
        self.collide = False

    # 定义小球移动方法

    def move(self):
        if self.control:
            newSpeed = self.speed
        else:
            newSpeed = [self.speed[0] * self.side[0],
                        self.speed[1] * self.side[1]]
        self.rect = self.rect.move(newSpeed)
        # 边界检测
        if self.rect.right < 0:
            self.rect.left = self.width
        elif self.rect.left > self.width:
            self.rect.right = 0
        elif self.rect.top > self.height:
            self.rect.bottom = 0
        elif self.rect.bottom < 0:
            self.rect.top = self.height

    # 定一个方法检查小球是否达到目标

    def check(self, motion):
        if self.target <= motion <= self.target + 5:
            return True
        else:
            return False
